package com.crr.service.impl;

import com.crr.bean.CInquiry;
import com.crr.common.crud.BaseServiceImpl;
import com.crr.common.utils.DateUtils;
import com.crr.mapper.CConsultationDetailMapper;
import com.crr.mapper.CInquiryDetailMapper;
import com.crr.mapper.CInquiryMapper;
import com.crr.service.CInquiryService;
import com.crr.common.utils.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CInquiryServiceImpl extends BaseServiceImpl<CInquiry, CInquiryMapper> implements CInquiryService {
    @Autowired
    CInquiryDetailMapper cInquiryDetailMapper;
    @Autowired
    CConsultationDetailMapper cConsultationDetailMapper;

    @Transactional
    @Override
    public int save(CInquiry entity) {
        int res= super.save(entity);
        Assert.isNotSuccess(res, "保存询价单失败");
        if (null != entity.getEnquiryDetails() && entity.getEnquiryDetails().size() > 0) {
            res = cInquiryDetailMapper.batchSave(entity.getId(), entity.getEnquiryDetails());
            Assert.isNotSuccess(res, "询价明细保存失败");
            entity.setCode(generateInquiryCode());
        }else{
            res = cConsultationDetailMapper.saveConsult(entity.getId(), entity.getConsultDetails());
            Assert.isNotSuccess(res, "保存咨询明细失败");
            entity.setCode(generateConsultCode());
        }

        return 1;
    }

    String generateInquiryCode() {
        String ym = DateUtils.getYm();
        String code="XJD"+ym;
        //查询当月最大编码
        code = queryMaxCode(ym,code);
        if (null == code) {
            return "XJD" + ym + "001";
        } else {
            int substring = Integer.parseInt(code.substring(3)) + 1;
            return "XJD" + substring;
        }
    }

    String generateConsultCode() {
        String ym = DateUtils.getYm();
        String code="ZXD"+ym;
        //查询当月最大编码
        code = queryMaxCode(ym,code);
        if (null == code) {
            return "ZXD" + ym + "001";
        } else {
            int substring = Integer.parseInt(code.substring(3)) + 1;
            return "ZXD" + substring;
        }
    }

    @Override
    public String queryMaxCode(String ym,String code) {
        return baseMapper.queryMaxCode(ym,code);
    }


}